package rmi.attempt2.server;

import rmi.attempt2.net.*;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import java.net.InetAddress;

public class Server {

	public static final void main(String[] args) throws Exception {
		final int port = 40004;
		final String EVENT_HANDLER_BIND = "eventHandler";
		Registry rmiregistry = null;
		try {
			System.out.println("IP of my system is");
			System.out.println(java.net.Inet4Address.getLocalHost().getHostAddress());
			System.setProperty("java.rmi.server.hostname", java.net.Inet4Address.getLocalHost().getHostAddress());
			// start rmi registry
			rmiregistry = LocateRegistry.createRegistry(port);
			// create EventHandler
			EventHandlerImpl eh = new EventHandlerImpl();
			eh.addChatEventListener(new ChatEventListener() {
				public void chatMessage(ChatEvent event) {
					System.out.println("<Server> recieved message: ["+event.origin+"] ["+event.message+"]");
					try { Thread.sleep(1000); } catch (Exception e) { throw new RuntimeException(e); }
				}
			});
			// bind EventHandler
			rmiregistry.rebind(EVENT_HANDLER_BIND, eh);
			System.out.println("<Server> bound EventHandler to "+EVENT_HANDLER_BIND);
			while(true); // wait for ctrl-c
		} catch(Exception e) { e.printStackTrace(); 
		} finally {
            if (rmiregistry != null) UnicastRemoteObject.unexportObject(rmiregistry, true);
			System.out.println("exiting");
            System.exit(0);
        }

	}

}

